<template>
    <div class="container">
        <div class="content_wrapper">
            <div class="lyecs-table-list-warp">
                <div class="list-table-tool lyecs-search-warp">
                    <el-form :model="filterParams">
                        <div class="list-table-tool-row">
                            <div class="list-table-tool-col">
                                <el-space>
                                    <el-input name="keyword" v-model="filterParams.keyword" placeholder="输入赠品名称">
                                        <template #append>
                                            <el-button @click="onSearchSubmit"><span
                                                    class="iconfont icon-chakan1"></span></el-button>
                                        </template>
                                    </el-input>
                                </el-space>
                            </div>
                        </div>
                    </el-form>
                </div>
                <div class="table-container">
                    <a-spin :spinning="loading">
                        <el-table
                            ref="tableRef"
                            :class="isMultiple ? '' : 'hide-checkbox'"
                            :data="filterState"
                            :loading="loading"
                            :total="total"
                            class="result-table"
                            row-key="product_id"
                            @select="selectRow"
                            @selection-change="onSelectChange"
                        >
                        <el-table-column :selectable="isSelectable" type="selection" width="32" />
                            <el-table-column label="赠品名称" prop="gift_name" width="120"></el-table-column>
                            <el-table-column label="商品信息" prop="product_name">
                                <template #default="{ row }">
                                    <div class="product-info">
                                        <img :src="imageFormat(row.product_info.pic_thumb)" height="50" width="50" />
                                        <p>{{ row.product_info.product_name }}</p>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="赠品库存" prop="gift_stock" sortable="custom"></el-table-column>
                            <template #empty>
                                <div class="empty-warp">
                                    <div v-if="!loading" class="empty-bg">暂无数据</div>
                                </div>
                            </template>
                        </el-table>
                    </a-spin>
                    <div class="pagination-con" v-if="total > 0">
                        <Pagination v-model:page="filterParams.page" v-model:size="filterParams.size" :total="total"
                            @callback="loadFilter" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import '@/style/css/list.less'
import { DialogForm } from '@/components/dialog'
import { ref, reactive, onMounted } from 'vue';
import { DeleteRecord, Pagination } from '@/components/list';
import { message } from 'ant-design-vue'
import { ProductGiftFilterState, ProductGiftFilterParams } from '@/types/promotion/productGift.d';
import { getProductGiftList, delProductGift, batchSubmit } from "@/api/promotion/productGift";
import { useConfigStore } from "@/store/config"
import { imageFormat } from "@/utils/format";
import { truncate } from 'lodash-es';
const props = defineProps({
    // 已选择的项，用于排除重复，禁止选择
    selected_ids: { type: Array, default: [] },
    modelValue: {
        type: Object,
        default: {}
    },
    isMultiple: {
        type: Boolean,
        default: false
    }
});
const emit = defineEmits(["submitCallback", "okType", "update:modelValue"]);
emit("okType", false);
const selectedIds = ref<any[]>([]);
const config:any = useConfigStore();
// 基本参数定义
const filterState = ref<ProductGiftFilterState[]>();
const loading = ref<boolean>(true);
const total = ref<number>(0);
const filterParams = reactive<ProductGiftFilterParams>({
    page: 1,
    size: config.get('page_size'),
    sort_field: '',
    sort_order: '',
    keyword: ''
});
// 获取列表的查询结果
const loadFilter = async () => {
    loading.value = true;
    try {
        const result = await getProductGiftList({ ...filterParams });
        filterState.value = result.filter_result;
        total.value = result.total;
    } catch (error: any) {
        message.error(error.message);
    } finally {
        loading.value = false;
    }
}
onMounted(() => {
    loadFilter();
    // selectedIds.value = props.selected_ids;
});

// 参数查询
const onSearchSubmit = () => {
    loadFilter()
};
const tableRef: any = ref();

const onSelectChange = (e:any) => {
    if (props.isMultiple) {
        e.forEach((item:any) => {
            // 创建一个 Set 包含当前 selectedIds.value 的所有项
            const idsSet = new Set(selectedIds.value);
            // 尝试向 Set 中添加新的
            idsSet.add(item);
            // 使用 Set 的唯一性质，将其转换回数组赋给 selectedIds.value
            selectedIds.value = Array.from(idsSet);
        });
        emit("okType", (selectedIds.value.length > 0));
    }
}

const selectRow = (selection:any, val:any) => {
    //手动触发该事件
    if (!props.isMultiple) {
        // 单选
        tableRef.value.clearSelection();
        if (selection.length == 0) {
            selectedIds.value = []; // 清空data中绑定的selectedRow
            return;
        }
        tableRef.value.toggleRowSelection(val, true);
        selectedIds.value.length = 0;
        selectedIds.value.push(val);
        emit("okType", selectedIds.value.length > 0);
    }
    // selectedIds.value = selection
    emit("update:modelValue", val);
}
const isSelectable = (row:any, rowIndex:number) => {
    // 排除重复项
    let ids:any[] = [];
    props.selected_ids.map((item:any) => {
        ids.push(item.gift_id)
    })
    return !ids.includes(row.gift_id)
}
// 弹窗回调
const onFormSubmit = () => {
    // 弹窗确认按钮提交
    emit("submitCallback", selectedIds.value);
};

// 修改排序

defineExpose({
    onFormSubmit
});

</script>
<style lang="less" scoped>
.product-info{
    display: flex;
    align-items: center;
    img{
        margin-right: 10px;
    }
}
.pagination-con {
    background: #fff;
}
:deep .hide-checkbox .el-table__header-wrapper .el-table__header .el-checkbox {
    display: none;
}
.container{
    :deep(.el-table__header-wrapper .el-table-column--selection > .cell){
        display: none;
    }
}
</style>